﻿Imports System.IO
Public Class frmTrichLuuDuLieu
    Public isTrichLuu As Boolean = False
    Private strFolderDLMoi As String
    Private strLogFile As String
    Private strDataFile As String
    Private strTenCSDL As String
    Private bangThongTinTrichLuu As New DataTable()
    Private Sub btBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btBrowse.Click
        'mo form cho nguoi ta chon co so du lieu
        FolderBrowserDialog.SelectedPath = ""
        txtFolderName.Text = ""
        FolderBrowserDialog.ShowDialog()
        txtFolderName.Text = FolderBrowserDialog.SelectedPath()
    End Sub
    Private Function TaoCSDL() As Boolean
        Dim kq As Boolean = True
        Dim strFileBackUp As String = Application.StartupPath() & "\" & strTenCSDL & ".dat"
        Me.Cursor = Cursors.WaitCursor
        Try
            File.Delete(strFileBackUp)
        Catch ex As Exception
        End Try
        Dim strOldDB As String = XL_DULIEU.LayGiaTriThanhPhan("Initial Catalog")
        'dau tien la doc thong tin ve co so du lieu can trich lu va lay ra ten cua logical logfile va datafile
        Dim bangFileLogic As New DataTable()
        XL_DULIEU.LayDuLieuRaBang("select groupid, name from sysfiles", bangFileLogic)
        Dim strOldDataFile As String = ""
        Dim strOldLogFile As String = ""
        If (bangFileLogic.Rows.Count > 0) Then
            strOldDataFile = bangFileLogic.Select("groupid=1")(0)(1)
            strOldLogFile = bangFileLogic.Select("groupid=0")(0)(1)
        End If

        'tao file back up cua co so du lieu Kho706
        Dim cauLenh As String = " BACKUP DATABASE [" & strOldDB & "] To Disk ='" & strFileBackUp & "'"
        'thuc hien restore
        cauLenh &= " RESTORE FILELISTONLY FROM Disk = '" & strFileBackUp & "'"
        cauLenh &= " RESTORE DATABASE [" & strTenCSDL & "] FROM Disk = '" & strFileBackUp & "' WITH RECOVERY,"
        cauLenh &= " MOVE '" & strOldDataFile.Trim() & "' TO '" & strDataFile & "',"
        cauLenh &= " MOVE '" & strOldLogFile.Trim() & "' TO '" & strLogFile & "'"

        'sau khi thuc hien thanh cong lenh o tren moi tiep tuc thuc hien lenh insert
        If (XL_DULIEU.ThucHienLenh(cauLenh) = False) Then
            kq = False
            Me.Cursor = Cursors.Arrow
            Return kq
        End If
        'them mot dong thong tin ve cach luu tru du lieu vao Database chinh va database moi tao
        cauLenh = " insert into tblTrichLuu values (GetDate(),'" & g_UserName & "','" & strTenCSDL & "','" & strFolderDLMoi & "')"
        cauLenh &= " insert into [" & strTenCSDL & "].[dbo].[tblTrichLuu] values(GetDate(),'" & g_UserName & "','" & strTenCSDL & "','" & strFolderDLMoi & "')"
        'cau lenh nay chi thanh cong khi nguoi dang nhap la nguoi quan tri he thong
        'tuc la nguoi dang nhap co quyen System Administrator
        If (XL_DULIEU.ThucHienLenh(cauLenh) = False) Then
            kq = False
            Me.Cursor = Cursors.Arrow
            Return kq
        End If
        'them mot dong moi vao bangThongTinTrichLuu
        Dim dong As DataRow = bangThongTinTrichLuu.NewRow()
        dong("ngaygio") = DateTime.Now()
        dong("nguoitrich") = g_UserName
        dong("tenCSDL") = strTenCSDL
        dong("thuMuc") = strFolderDLMoi
        bangThongTinTrichLuu.Rows.Add(dong)
        gridTrichLuu.Refresh()
        Try
            File.Delete(strFileBackUp)
        Catch ex As Exception
        End Try
        Me.Cursor = Cursors.Arrow
        Return kq
    End Function

    Private Sub btDongForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btDongForm.Click
        Me.Close()
    End Sub

    Private Sub btDongY_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btDongY.Click
        'kiem tra chi cho trich luu tai may chu - noi chua du lieu
        Dim tenMayChuChuaDuLieu As String = XL_DULIEU.LayGiaTriThanhPhan("Data Source")
        'If (tenMayChuChuaDuLieu <> Environment.MachineName) Then
        '    MessageBox.Show("Chỉ hỗ trợ trích lưu tại máy chủ chứa dữ liệu!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    Exit Sub
        'End If
        'kiem tra xem nguoi dung co nhap du thong tin
        If (txtTenCSDL.Text = "") Then
            MessageBox.Show("Tên cơ sở dữ liệu chưa có!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If
        If (txtFolderName.Text = "" And strFolderDLMoi = "") Then
            MessageBox.Show("Chưa chọn thư mục chứa dữ liệu!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        Else
            If (txtFolderName.Text = "") Then
                txtFolderName.Text = strFolderDLMoi
            Else
                strFolderDLMoi = txtFolderName.Text
            End If
        End If
        strTenCSDL = txtTenCSDL.Text
        'kiem tra xem ten thu muc va ten co so du lieu co qua dai hay khong
        If (txtFolderName.Text.Length > 255) Then
            MessageBox.Show("Tên thư mục không được quá 255 ký tự!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
        If (txtTenCSDL.Text.Length > 50) Then
            MessageBox.Show("Tên CSDL không được quá 50 ký tự!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If

        'tao du lieu moi
        'tao ten co so du lieu moi
        strLogFile = strFolderDLMoi & "\" & strTenCSDL & "_Log.ldf"
        strDataFile = strFolderDLMoi & "\" & strTenCSDL & "_Data.mdf"

        If (TaoCSDL() = False) Then
            isTrichLuu = False
            MessageBox.Show("Trích lưu không thành công. Có thể bạn không có quyền trích lưu!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            isTrichLuu = True
            MessageBox.Show("Trích lưu thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.Close()
        End If
    End Sub

    Private Sub frmTrichLuuDuLieu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'chon thu muc cai dat SQL server
        strFolderDLMoi = My.Computer.FileSystem.SpecialDirectories.ProgramFiles & "\Microsoft SQL Server\MSSQL\Data"
        'kiem tra xem duong dan nay co khong
        Dim thuMucSQL As DirectoryInfo = New DirectoryInfo(strFolderDLMoi)
        If (thuMucSQL.Exists = True) Then
            txtFolderName.Text = strFolderDLMoi
        Else
            strFolderDLMoi = ""
        End If
        txtTenCSDL.Text = "Kho706_" + Date.Now.Day.ToString() + "-" + Date.Now.Month.ToString() + "-" + Date.Now.Year.ToString()
        'load thong tin ve viec trich luu len
        XL_DULIEU.LayDuLieuRaBang("select * from tblTrichLuu", bangThongTinTrichLuu)
        gridTrichLuu.DataSource = bangThongTinTrichLuu
    End Sub
End Class